package com.atguigu.gulimall.product.service.impl;

import ch.qos.logback.core.rolling.TimeBasedFileNamingAndTriggeringPolicy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2VO;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    //    private Map<String,Object> cache=new HashMap<>();
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
//        log.info("size:{}",entities.size());
//        log.info("entities:{}",entities);
        //2.组装成父子的树形结构

        //2.1找到所有的1级分类（父分类id是0）
        List<CategoryEntity> levelMenus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return levelMenus;
    }
    public List<CategoryEntity> myListWithTree(){
        List<CategoryEntity> all = this.baseMapper.selectList(null);
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(categoryEntity -> {
            categoryEntity.setChildren(myGetChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((e1, e2) -> {
            return (e1.getSort() == null ? 0 : e1.getSort()) - (e2.getSort() == null ? 0 : e2.getSort());
        }).collect(Collectors.toList());
        return collect;

    }
    private List<CategoryEntity> myGetChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((e1, e2) -> {
            return (e1.getSort() == null ? 0 : e1.getSort()) - (e2.getSort() == null ? 0 : e2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }
    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity) -> {
            //1.递归查找子菜单
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2.菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查要被删除的菜单是否被别的地方引用
        ArrayList<Long> delete_ids = new ArrayList<>();
        for (Long id : asList) {
            List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", id));
            if(categoryEntities!=null||categoryEntities.size()!=0){
                //有别的地方引用，无法删除
            }else{
                delete_ids.add(id);
            }
        }
        //逻辑删除
        baseMapper.deleteBatchIds(delete_ids);

    }

    /**
     * 找到catlogid的完整路径：
     * [父/子/孙子] [2/25/225]
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    public Long[] myFindCatelogPath(Long catelogId){
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    private List<Long> myFindParentPath(Long catelogId,List<Long>paths){
        paths.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if(categoryEntity.getParentCid()!=0){
            myFindParentPath(categoryEntity.getParentCid(),paths);
        }
        return paths;
    }
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1.收集当前节点id
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }
    /**
     * 级联更新所有关联的数据
     * @CacheEvict 失效模式
     * 1.同时进行多种缓存操作   @Caching
     * 2.指定删除某个分区所有数据   @CacheEvict(value = "category",allEntries = true)
     * 3.存储同一类型的数据 都可以指定成同一个分区 这样只要修改这个分区的数据 缓存可以批量删除。分区名默认就是缓存的前缀
     * @param category
     */

//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Categories'"),
//            @CacheEvict(value = "category",key = "'getCatelogJson'")
//    })
    @CacheEvict(value = "category",allEntries = true)//删除缓存中category分区，这样下次查询，缓存里就是更新的Catelog了
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        //保证冗余字段数据一致
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
        //同时修改缓存中的数据
        //redis.delete("catelogJson");等待下一次主动查询进行更新
    }

    //每一个需要缓存的数据我们都要指定要放到哪个名字的缓存中【缓存的分区（按照业务类型分）】
    //

    /**
     * 默认行为
     *  1.缓存中有 方法不调用
     *  2.key默认自动生成：  缓存名字：：SimpleKey [](自主生成的key值)
     *  3.value值默认使用jdk序列化机制将序列化后的数据存到redis
     *  4.默认时间是-1，永不过期
     * 自定义：
     *  1.指定生成的缓存使用的key key属性指定，接收一个SpEL
     *  2.指定缓存数据存活的时间 配置文件中修改ttl
     *  3.将数据保存为json格式
     *      CacheAutoConfiguration
     *      RedisCacheConfiguration
     * @return
     */
    //

    @Cacheable(value = {"category"},key = "#root.methodName",sync = true) //代表当前方法的结果需要缓存，如果缓存中有，方法不用调用，如果缓存中没有，会调用方法最后将方法返回结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Categories() {
        System.out.println("getLevel1Categories...");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间：" + (System.currentTimeMillis() - l));
        return categoryEntities;
    }
    @Cacheable(value = {"category"},key = "#root.methodName",sync = true)
    public List<CategoryEntity> myGetLevel1Catagories(){
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = {"category"},key =  "#root.methodName")
    @Override
    public Map<String, List<Catelog2VO>> getCatelogJson() {
        /**
         * 1.将数据库的多次查询变为1次
         *
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查出所有1级分类
        List<CategoryEntity> level1Categories = getParent_cid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catelog2VO>> collect = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每一个的1级分类，查到这个一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2.封装上面的结果
            List<Catelog2VO> catelog2VOList = null;
            if (categoryEntities != null) {
                catelog2VOList = categoryEntities.stream().map(l2 -> {
                    Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找二级分类的三级分类 封装为vo
                    List<CategoryEntity> level3List = getParent_cid(selectList, l2.getCatId());
                    if (level3List != null) {
                        List<Catelog2VO.Catelog3VO> collect1 = level3List.stream().map(l3 -> {
                            Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                        catelog2VO.setCatalog3List(collect1);
                    }
                    return catelog2VO;
                }).collect(Collectors.toList());
            }

            return catelog2VOList;
        }));

        return collect;

    }

    @Cacheable(value = {"category"},key = "#root.methodName")
    public Map<String,List<Catelog2VO>> myGetCatelogJson(){
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.找出第一层的商品类别
        List<CategoryEntity> categoryEntities = getParent_cid(selectList, 0L);

        Map<String, List<Catelog2VO>> collect = categoryEntities.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个1级分类，查出这个一级分类的所有二级分类
            List<CategoryEntity> level2CategoriesList = getParent_cid(selectList, v.getCatId());
            List<Catelog2VO> catelog2VOList = null;
            if (level2CategoriesList != null) {
                catelog2VOList = level2CategoriesList.stream().map(l2 -> {
                    Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //查出2级分类的所有3级分类
                    List<CategoryEntity> level3CategoriesList = getParent_cid(selectList, l2.getCatId());
                    List<Catelog2VO.Catelog3VO> catelog3VOS = null;
                    if (level3CategoriesList != null) {
                        catelog3VOS = level3CategoriesList.stream().map(l3 -> {
                            Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                    }
                    catelog2VO.setCatalog3List(catelog3VOS);
                    return catelog2VO;
                }).collect(Collectors.toList());
            }
            return catelog2VOList;
        }));
        return collect;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
    }

    private List<CategoryEntity> myGetParentCid(List<CategoryEntity> selectList,Long parent_cid){
        return selectList.stream().filter(categoryEntity -> categoryEntity.getParentCid()==parent_cid).collect(Collectors.toList());
    }
    //TODO 产生堆外内存溢出 OutOfDirectMemoryError
    //1.springboot2.0以后 默认使用lettuce作为操作redis的客户端 使用netty进行网络通信
    //2.lettuce的bug导致netty堆外内存溢出 -Xmx300m:netty如果不指定堆外内存，默认使用-Xmx300m
    // 解决方案：不能只去调整虚拟机参数调大堆外内存，
    //1.升级lettuce客户端        2.切换使用jedis客户端
    // redisTemplate:
    // lettuce jedis 操作redis的底层客户端。Spring再次封装成redisTemplate

    public Map<String, List<Catelog2VO>> getCatelogJson2() {
        //给缓存中放json字符串，拿出的json字符串逆转为能用的对象类型【序列化与反序列化的过程】

        /**
         * 1.空结果缓存（缓存穿透）
         * 2.设置过期时间+随机值（缓存雪崩）
         * 3.加锁（缓存击穿 ）
         */

        //加入缓存逻辑，缓存中存储的对象都是一个json字符串
        //json好处是跨语言跨平台兼容
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) {
            System.out.println("缓存不命中...查询数据库...");
            //缓存中没有数据,查询数据库
            Map<String, List<Catelog2VO>> catelogJsonFromDb = getCatelogJsonWithRedeissonLock();
            //查到的数据放入缓存,将对象转为json放入缓存
//            String s = JSON.toJSONString(catelogJsonFromDb);
//            redisTemplate.opsForValue().set("catelogJson",s,1, TimeUnit.DAYS);
            return catelogJsonFromDb;
        }
        System.out.println("缓存命中...直接返回...");
        //逆转为指定的对象
        Map<String, List<Catelog2VO>> result = JSON.parseObject(catelogJson,
                new TypeReference<Map<String, List<Catelog2VO>>>() {
                });
        return result;
    }

    /**
     * 缓存中的数据如何和数据库保持一致
     * 缓存数据一致性
     * 1）双写模式
     * 2）失效模式
     * @return
     */
    public Map<String, List<Catelog2VO>> getCatelogJsonWithRedeissonLock() {
        //1.锁的名字。锁的粒度越细 运行越快 并发读越高
        //锁的粒度 具体缓存的是某个数据   11号商品:product-11-lock  product-12-lock
        RLock lock = redisson.getLock("catelogJson-json");
        lock.lock();
        Map<String, List<Catelog2VO>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    public Map<String,List<Catelog2VO>> myGetCatelogJsonWithRedissonLock(){
        RLock lock = redisson.getLock("catelogJson-json");
        lock.lock();
        Map<String,List<Catelog2VO>> dataFromDb;
        try {
            dataFromDb=getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }
    private Map<String, List<Catelog2VO>> getDataFromDb() {
        //得到锁以后 我们应该再去缓存确定一次，如果没有才需要继续查询
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (!StringUtils.isEmpty(catelogJson)) {
            //缓存不为null 直接返回
            Map<String, List<Catelog2VO>> result = JSON.parseObject(catelogJson,
                    new TypeReference<Map<String, List<Catelog2VO>>>() {
                    });
            return result;
        }
        System.out.println("查询了数据库......");
        /**
         * 1.将数据库的多次查询变为1次
         *
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查出所有1级分类
        List<CategoryEntity> level1Categories = getParent_cid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catelog2VO>> collect = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每一个的1级分类，查到这个一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2.封装上面的结果
            List<Catelog2VO> catelog2VOList = null;
            if (categoryEntities != null) {
                catelog2VOList = categoryEntities.stream().map(l2 -> {
                    Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找二级分类的三级分类 封装为vo
                    List<CategoryEntity> level3List = getParent_cid(selectList, l2.getCatId());
                    if (level3List != null) {
                        List<Catelog2VO.Catelog3VO> collect1 = level3List.stream().map(l3 -> {
                            Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                        catelog2VO.setCatalog3List(collect1);
                    }
                    return catelog2VO;
                }).collect(Collectors.toList());
            }

            return catelog2VOList;
        }));
        //查到的数据放入缓存,将对象转为json放入缓存
        String s = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("catelogJson", s, 1, TimeUnit.DAYS);
        return collect;
    }
    private Map<String,List<Catelog2VO>> myGetDataFromDb(){
        String catalogJson=redisTemplate.opsForValue().get("catelogJson");
        if(!StringUtils.isEmpty(catalogJson)){
            Map<String, List<Catelog2VO>> result = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catelog2VO>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库");
        /**
         * 将数据库的多次查询变为1次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //1.查询所有1级分类
        List<CategoryEntity> level1Categories = getParent_cid(selectList, 0L);
        Map<String, List<Catelog2VO>> collect = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //得到该1级分类下的所有2级分类
            List<CategoryEntity> level2Categories = getParent_cid(selectList, v.getCatId());
            List<Catelog2VO> catelog2VOList = null;
            if (level1Categories != null) {
                catelog2VOList = level2Categories.stream().map(l2 -> {
                    Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> level3Categories = getParent_cid(selectList, l2.getCatId());
                    List<Catelog2VO.Catelog3VO> catelog3VOList = null;
                    if (level3Categories != null) {
                        catelog3VOList = level3Categories.stream().map(l3 -> {
                            Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                    }
                    catelog2VO.setCatalog3List(catelog3VOList);
                    return catelog2VO;
                }).collect(Collectors.toList());
            }
            return catelog2VOList;
        }));
        //查出的数据转成json格式放入缓存
        String s=JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("catelogJson",s,1,TimeUnit.DAYS);
        return collect;
    }
    //从数据库查询并封装分类数据
    public Map<String, List<Catelog2VO>> getCatelogJsonWithLocalLock() {
        //        //1.如果缓存中有就用缓存的
//        Map<String, List<Catelog2VO>> catelogJson = (Map<String, List<Catelog2VO>>) cache.get("catelogJson");
//        if(cache.get("catelogJson")==null){
        //调用业务
        //返回数据又放入缓存
//              cache.put("catelogJson",collect);
//        }
//        return catelogJson;
        //只要是同一把锁，就能锁住需要锁的所有线程
        //1.synchronized (this) :springboot所有的组件在容器中都是单例的
        //TODO 本地锁：synchronized juc（lock）,在分布式情况下，想锁住所有，必须使用分布式锁
        synchronized (this) {
            //得到锁以后 我们应该再去缓存确定一次，如果没有才需要继续查询
            return getDataFromDb();
        }

    }


    public Map<String, List<Catelog2VO>> getCatelogJsonWithRedisLock() {
        //1.占分布式锁 去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功...");
            //加锁成功 执行业务...
            //设置过期时间 必须和加锁是同步的，原子的
//            redisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<String, List<Catelog2VO>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                //获取值对比+对比成功进行删锁=原子操作 lua脚本解锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }

//            redisTemplate.delete("lock");//删除锁


//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(lockValue.equals(uuid)){
//                //删除我自己的锁
//                redisTemplate.delete("lock");
//            }

            return dataFromDb;

        } else {
            //加锁失败 进行重试...
            //休眠100ms
            System.out.println("获取分布式锁失败，等待重试...");
            return getCatelogJsonWithRedisLock();//自旋的方式
        }
    }

    //redis实现分布式锁
    public Map<String,List<Catelog2VO>> myGetCatelogJsonWithRedisLock(){
        //1.占redis分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if(lock){
            Map<String,List<Catelog2VO>> dataFromDb=null;
            try {
                dataFromDb=getDataFromDb();
            } finally {
                //获取值对比+对比成功进行删锁=原子操作 lua脚本解锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }
            return dataFromDb;
        }else {
            //加锁失败，进行重试
            System.out.println("获取分布式锁失败，等待重试" );
            return myGetCatelogJsonWithRedisLock();//自旋的方式
        }
    }






}